﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;


namespace keygen
{
    public class RSA
    {
        /* private static string privateKey = @"<RSAKeyValue><Modulus>0b0IRCO+VfGFnZZi9EiiKvUmFFKUy20YyUF+mSChj5CLF1w5wJKZAmgTbw
 OR/ZyfVCDK5kdd2DYpfErOifloAfjxJazV4MnLxWoZuH1pfFdpSW6ioRetHrsLB5RQOhNiF/L5OpBQBc
 2DJaCcuTkNTa05b78hYU3tSMLn3+BtG/U=</Modulus><Exponent>AQAB</Exponent><P>9rb6FFSa
 HcOiS9dB8vOxkwwo55c/z/1GaDSzvNZtfC6lrRTfkmQa55IYAYfFSfMctI61I06L+Rg48CNWMyqmTw==
 </P><Q>2aHMoa8+MA/A/1ZytyZNd4ah/M7rOBr1jvjA+r87h60bUYUKWTLBhElTceGwpm0kEdc+QfNiP
 /e3EE1lxUSMew==</Q><DP>iH1oUxEPBkJyKmUXTjK13fVPN/i8S/QCHKpzeZhjj906uUuf+Jw7Kjvv3
 gDgC+5cxiNhYPwWgiN9dJUIHlyNDw==</DP><DQ>Z4VlV0uKo0X7Ifo3GxOnKcHq79xlWwzH3bhJ43xv
 jrwzEHXeVEumbYyLmtImOyQTUkE2phxlkdP9Sk3mqQ1QXQ==</DQ><InverseQ>ZzfD0cLmiMLFXxdQs
 m30SGEWtV21FMb5yh2TEtMRhsNLtDT8PH8H6F2DG39CheLEua1SedWTV9PSvWRtyBoW5A==</Inverse
 Q><D>gvWuaKWM3ir9jCVvyipkH8CMs1nREKghNuEPRFvMpVDSmJZ8dRLUOV107Pdku9+E2MnVBy5+mVd
 QVgx7pEk3uAmhAoLJKIUH1XSLV+QkmQ9WSxLTp8AY7fLwshfi4lq4Pik+LqN7/iu8yBIbFSMW8pxaZyX
 S0Q+xGg/qxl+/+k0=</D></RSAKeyValue>";

         private static string publickey = @"<RSAKeyValue><Modulus>0b0IRCO+VfGFnZZi9EiiKvUmFFKUy20YyUF+mSChj5CLF1w5wJKZAmgTbw
 OR/ZyfVCDK5kdd2DYpfErOifloAfjxJazV4MnLxWoZuH1pfFdpSW6ioRetHrsLB5RQOhNiF/L5OpBQBc
 2DJaCcuTkNTa05b78hYU3tSMLn3+BtG/U=</Modulus><Exponent>AQAB</Exponent></RSAKeyVal
 ue>";
 */

        private static string privateKeyStr = @"<RSAKeyValue><Modulus>sJSNXb3+DSXdZ5raDgC7OaJ51NZMLxz2PeaVBQswYtwikQJlVYc+fXFFco
1GKS5cnseumF4DSqcTCRf89GIOezvqTk3/MgG+820k2b6B+BvtTNnA41eKbd62proa2LlPlnwd9ldUA+
sFnQePe7walN3DeCDjKVexNI1WwJVPyvE=</Modulus><Exponent>AQAB</Exponent><P>2F8epbCX
YA9wIFAcsKow/PqRhvBbj88YFhieBTIPGZVvPZLRkh4juq3j3fEVrSkR2Z41AUJNzN3uKMHC8WJNzw==
</P><Q>0OvDZTJVRp9GIWHkb0zO7RUehCQPcahx9SkmVoIQP1HIxW/6MvYrHOBn0NCf13moqo5G8z8Re
xLR6uVkeT1LPw==</Q><DP>rjsiLZ/etU6ZJpv8DlJtsjh/GR7RTCMiLSDTljFyMVLAyd9A/J1iff9qf
xyULOTmZ8tauVHP3klTbuRf+woCxw==</DP><DQ>dIpvju3K4ABNEKYY1XVVIK9dPH0ZGF/MYeO4fR1E
ju3CP1C9ktv7JLqRbsxRvdMhoTKIpXwS9kKDUrLvnynv5Q==</DQ><InverseQ>VTxk6HRHV0yApvex1
QvEMkHkYYoWUeN5N639IIu22P6AAUctrMVWakIBPjL9U86Bb/u1lI7xLRUeFJS7OuRPEQ==</Inverse
Q><D>B7z61PjWgUz/fuLSW3q8ubHdFO6vOAFU6TGJpkbvP+XVvfUU68KZgnXMTVDTmkpl1K97f0Hfcw4
PT361nyAM8lbylZP7US7Eb2nQBp4sCORmidCkzkE3YrSJksIATm9jI4C7KApwsEbCG9aAbgdQQUlbzIF
FZ8146aHLiDLOteE=</D></RSAKeyValue>";

        private static string publicKeyStr = @"<RSAKeyValue><Modulus>sJSNXb3+DSXdZ5raDgC7OaJ51NZMLxz2PeaVBQswYtwikQJlVYc+fXFFco
1GKS5cnseumF4DSqcTCRf89GIOezvqTk3/MgG+820k2b6B+BvtTNnA41eKbd62proa2LlPlnwd9ldUA+
sFnQePe7walN3DeCDjKVexNI1WwJVPyvE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        /// <summary>
        /// 私钥签名
        /// </summary>
        /// <param name="sign">签名Str</param>
        /// <param name="validStr">需要验证的validStr</param>
        /// <returns></returns>
        public static string SignData(string sign)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            UnicodeEncoding unicode = new UnicodeEncoding();
            byte[] signbytes = unicode.GetBytes(sign);
            rsa.FromXmlString(privateKeyStr);
            return Convert.ToBase64String(rsa.SignData(signbytes, new SHA1CryptoServiceProvider()));
        }


        /// <summary>
        /// 公钥验证签名
        /// </summary>
        /// <param name="sign">签名Str</param>
        /// <param name="validStr">需要验证的validStr</param>
        /// <returns></returns>
        public static bool varifySign(string sign, string validStr)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] signbytes = Convert.FromBase64String(sign);
            byte[] validStrbytes = Encoding.Unicode.GetBytes(validStr);
            rsa.FromXmlString(publicKeyStr);
            bool isVarify = false;
            isVarify = rsa.VerifyData(validStrbytes, new SHA1CryptoServiceProvider(), signbytes);
            return isVarify;
        }


        /// <summary>
        /// 公钥字符串加密
        /// </summary>
        /// <param name="sourceData"></param>
        /// <returns></returns>
        public static string longStringRSApublicEncry(string  sourceData)
        {
            RSACryptoServiceProvider rsa = new  RSACryptoServiceProvider();
            byte[] data =System.Text.Encoding.Default.GetBytes(sourceData);

            //要加密的数据
            string publicKey = publicKeyStr;  //获取私钥加密
            rsa.FromXmlString(publicKey);
            int keySize = rsa.KeySize / 8;
            int bufferSize = keySize - 11;
            byte[] buffer = new byte[bufferSize];

            MemoryStream msInput = new  MemoryStream(data);
            MemoryStream msOutput = new MemoryStream();
            int readLen = msInput.Read(buffer, 0, bufferSize);

            while (readLen > 0)
            {
                byte[] dataToEnc = new byte[readLen];
                Array.Copy(buffer, 0, dataToEnc, 0, readLen);
                byte[] encData = rsa.Encrypt(dataToEnc, false);
                msOutput.Write(encData, 0, encData.Length);
                readLen = msInput.Read(buffer, 0, bufferSize);
            }
            msInput.Close();
            byte[] result = msOutput.ToArray();
            //得到加密结果
            msOutput.Close();
            rsa.Clear();
            string returnStr = Convert.ToBase64String(msOutput.ToArray());
            return returnStr;
        }
        /// <summary>
        /// 私钥解密，字符串解密
        /// </summary>
        /// <param name="sourceData"></param>
        /// <returns></returns>
        public static  string longStringRSAPrivateDescry(string  sourceData)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] key = System.Text.Encoding.Default.GetBytes(privateKeyStr);    //加载私钥
            string privateKey = Encoding.ASCII.GetString(key);
            byte[] dataEnc =Convert.FromBase64String(sourceData);   //加载密文
            rsa.FromXmlString(privateKey);
            int keySize = rsa.KeySize / 8;
            byte[]
            buffer = new byte[keySize];

            MemoryStream msInput = new MemoryStream(dataEnc);
            MemoryStream msOutput = new MemoryStream();
            int readLen = msInput.Read(buffer, 0,keySize);
            while (readLen > 0)
            {
                byte[] dataToDec = new byte[readLen];
                Array.Copy(buffer, 0, dataToDec,0, readLen);
                byte[] decData = rsa.Decrypt(dataToDec, false);
                msOutput.Write(decData, 0, decData.Length);
                readLen = msInput.Read(buffer, 0, keySize);
            }
            msInput.Close();
            byte[] result = msOutput.ToArray();
            //得到解密结果
            msOutput.Close();
            rsa.Clear();
            string returnStr=Encoding.ASCII.GetString(msOutput.ToArray());
   
            return returnStr;

        }
    }
}
